import { getDict } from "~/utils";
import {
    getInspectionitem,
    addInspectionitem,
    putInspectionitem,
    delInspectionitem
} from "../../../api/catalogue-check";
import { downloadPost } from "../../../api/check-in.js";
import { downloadBlob } from "@/utils";
export default {
    provide () {
        return {
            initList: this.getListData
        };
    },
    data () {
        return {
            // 编目弹框标题
            title: "",
            // 编目增改查弹框控制
            dialogVisible: false,
            // 表单项宽度
            formLabelWidth: "120px",
            //检查编目列表
            tableData: [],
            // 请求参数
            params: {
                current: 1,
                size: 10,
                inspectionName: "",
                projectType: ""
            },
            // 分页
            pager: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            //勾选列表
            selectDataArr: [],
            // 过滤检索配置
            filterList: [
                {
                    label: "物业类型",
                    inputType: "dict",
                    name: "projectType",
                    dictName: "property_types",
                    multiple: true
                }
            ],
            // 物业类型字典列表
            propertyTypes: [],

            // 检查项 增改表单校验规则
            rules: {
                // 排序规则
                sort: [
                    {
                        required: true,
                        message: "请输入排序",
                        trigger: "blur"
                    }
                ],
                // 物业类型校验规则
                projectType: [
                    {
                        required: true,
                        message: "请选择物业类型",
                        trigger: "blur"
                    }
                ],
                //检查项校验规则
                inspectionName: [
                    {
                        required: true,
                        message: "请输入检查项名称",
                        trigger: "blur"
                    },
                    {
                        min: 1,
                        max: 10,
                        message: "请确认长度在 1 到 10 个字符",
                        trigger: "blur"
                    }
                ]
            },
            // 编目增改查表单
            form: {
                inspectionName: "",
                projectType: "",
                remarks: "",
                sort: null
            }
        };
    },
    mounted () {
        //获取物业类型（字典）
        const propertyTypes = getDict("property_types");
        this.propertyTypes = propertyTypes;
        //触发物业类型选中并高亮第一项
        this.setCurrent(propertyTypes[0]);
    },
    methods: {
        // 物业类型格式化
        propertyTypeFormatter (row, column, cellValue) {
            let type = this.propertyTypes.find(p => p.value == cellValue);
            return type ? type.label : "";
        },
        // 菜单点击监听
        handleMenuClick (type) {
            switch (type) {
                case "add":
                    this.showAddOrEdit("add");
                    break;
                case "delete":
                    this.handleDelete();
                    break;
                case "export":
                    this.exportTable();
                    break;
                default:
                    break;
            }
        },
        //导出
        async exportTable () {
            // this.$refs.planningExport.show(this.searchForm)
            var time = new Date();
            var name =
                time.getFullYear() +
                "-" +
                (time.getMonth() + 1) +
                "-" +
                time.getDate() +
                " " +
                time.getHours() +
                ":" +
                time.getMinutes() +
                ":" +
                time.getSeconds() +
                "检查项列表.xls";
            var url = "/api/inspectionitem/exportInspectionItems";
            const rps = await downloadPost(url, {
                inspectionId: this.selectDataArr.map(e => e.inspectionId),
                projectType: this.params.projectType,
                inspectionName: this.params.inspectionName
            });
            downloadBlob(rps.data, name);
        },

        //选中并高亮物业类型第一项方法
        setCurrent (row) {
            this.$refs.singleTable.setCurrentRow(row);
        },
        //获取数据列表
        getListData (params = {}) {
            let req = {
                ...this.params,
                ...params
            };
            getInspectionitem(req)
                .then(res => {
                    const { current, size, total, records } = res.data.data;
                    this.tableData = records;
                    this.params = requestData;
                    this.pager = {
                        total,
                        currentPage: current,
                        pageSize: size
                    };
                    // 如果没有选中物业类型 调用左侧列表选中方法取消选中
                    (req.projectType == "" || req.projectType.length == 0) && this.setCurrent();
                })
                .catch(() => {
                    console.log("catch");
                });
        },
        //左侧物业类型   选择变化事件
        propertyTypeChange (row) {
            this.params.projectType = row.value ? row.value : ''
            this.getListData({
                current: 1,
                projectType: row.value
            });
        },
        //打开 新增/编辑   弹框  事件
        showAddOrEdit (v, row) {
            // 弹窗控制
            this.dialogVisible = true;
            switch (v) {
                case "add":
                    this.title = "新增检查项目";
                    this.form.projectType = this.params.projectType;
                    break;
                case "edit":
                    this.title = "编辑检查项目";
                    this.form = JSON.parse(JSON.stringify(row));
                    break;
            }
        },

        // 保存
        preservation (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.title == "新增检查项目") {
                        // 如果是新增
                        addInspectionitem(this.form)
                            .then(rps => {
                                if (rps.data.data.data !== 200) {
                                    this.$message({
                                        message: rps.data.data.msg,
                                        type: "warning"
                                    });
                                    return;
                                }
                                this.$message({
                                    message: rps.data.data.msg,
                                    type: "success"
                                });
                                this.dialogVisible = false;
                                this.getListData();
                            })
                            .catch(() => {
                                console.log("catch");
                            });
                    } else {
                        //如果是编辑
                        putInspectionitem(this.form)
                            .then(rps => {
                                if (rps.data.data.data !== 200) {
                                    this.$message({
                                        message: rps.data.data.msg,
                                        type: "warning"
                                    });
                                    return;
                                }
                                this.$message({
                                    message: rps.data.data.msg,
                                    type: "success"
                                });
                                this.dialogVisible = false;
                                this.getListData();
                            })
                            .catch(() => {
                                console.log("catch");
                            });
                    }
                } else {
                    return false;
                }
            });
            this.$refs[formName].clearValidate();
        },

        //检查项删除
        handleDelete () {
            if (!this.selectDataArr) return this.$alert("请勾选要删除的数据！");
            // 映射出所删除对应数据id数组
            let ids = this.selectDataArr.map(e => e.inspectionId);
            this.$confirm("此操作将永久删除该数据, 是否继续?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    delInspectionitem(ids)
                        .then(rep => {
                            this.getListData();
                            this.$message.success("删除成功");
                        })
                        .catch(e => {
                            this.$message.error("删除失败");
                        });
                })
                .catch(() => {
                    this.$message.info("已取消删除");
                });
        }
    }
};
